package com.example.util;

import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.PostConstruct;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Map;

@Service
public class EmailService {

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 发送邮件的配置对象，保存了在application.properties配置的邮件发送参数
     */
    @Autowired
    private MailProperties mailProperties;

    /**
     * 邮件模板配置对象
     */
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    /**
     * 发送邮件的帐号
     */
    private String sender;

    @PostConstruct
    public void init() {
        // 从邮件配置对象中获取发送邮件的帐号
        sender = mailProperties.getUsername();
    }

    /**
     * 发送文本邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param text    内容
     */
    public void sendTextMail(String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(sender);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        mailSender.send(message);
    }

    /**
     * 发送HTML内容的邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param html    内容
     */
    public void sendHtmlMail(String to, String subject, String html) {
        MimeMessage htmlMessage = null;
        try {
            htmlMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(htmlMessage, true);
            helper.setFrom(sender);
            helper.setTo(to);
            helper.setSubject(subject);

            // 第二个参数代表传入的是html字符串
            helper.setText(html, true);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        mailSender.send(htmlMessage);
    }


    /**
     * 发送带附件的邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     * @param html    boolean类型，true表示内容是html，false表示内容是文本
     * @param files   文件对数组
     */
    public void sendAttachmentsMail(String to, String subject, String content, boolean html, File[] files) {
        MimeMessage message = null;
        try {
            message = mailSender.createMimeMessage();
            // 第二个参数代表带有附件
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(sender);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, html);

            for (File file :
                    files) {
                if (file.isFile()) {
                    FileSystemResource resource = new FileSystemResource(file);
                    helper.addAttachment(file.getName(), resource);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mailSender.send(message);
    }


    /**
     * 发送带有静态资源的邮件，传入File对象
     *
     * @param to      收件人
     * @param subject 主题
     * @param html    包含cid占位的html字符串
     * @param model   Map集合，key表示cid的key值，value表示File对象
     */
    public void sendInlineMail(String to, String subject, String html, Map<String, File> model) throws MessagingException {
        MimeMessage message = null;
        message = mailSender.createMimeMessage();
        // 第二个参数代表带有附件
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(sender);
        helper.setTo(to);
        helper.setSubject(subject);

        helper.setText(html, true);

        for (Map.Entry<String, File> entry:
                model.entrySet()) {
            if (entry.getValue().isFile()) {
                FileSystemResource resource = new FileSystemResource(entry.getValue());
                helper.addInline(entry.getKey(), resource);
            }
        }

        mailSender.send(message);
    }


    /**
     * 发送模板邮件
     *
     * @param to           收件人
     * @param subject      主题
     * @param templateName 模板文件名
     * @param model        替换模板中占位的键值对集合
     */
    public void sendTemplateMail(String to, String subject, String templateName, Map<String, Object> model) throws Exception {
        MimeMessage message;
        message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        helper.setFrom(sender);
        helper.setTo(sender);
        helper.setSubject(subject);

        // 传入模板文件名，获取模板对象
        Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
        // 将模板对象和模板参数解析成html字符串
        String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);

        helper.setText(html, true);
        mailSender.send(message);
    }
}
